<?php
namespace Chat;
use \GatewayWorker\Lib\Db;
use Config\Db as DbConfig;

class Chat{
	/**
	 * Redis
	 */
	public $redis;

	public function __construct(){
        //连接Redis数据库
        $this->redis = new \Redis;
        if (!isset(DbConfig::$redis)) {
            echo "\\Config\\Db::$config_name not set\n";
            throw new Exception("\\Config\\Db::$redis not set\n");
        }
        $config = DbConfig::$redis;
        $this->redis->connect($config["host"], $config["port"]); 
	}

	/**
	 * 获取房间ID
	 * 聊天分两种，一个是单聊，另一个是群聊;单聊时传前两个参数,后面两个参数可省略；群聊时，前两个参数置空，chat_type传值group
	 * @param string 	$chat_type 	类型（group:群聊，friend:单聊）
	 * @param int 		$user_id 	用户ID（聊天两人中的自己的ID）
	 * @param int 		$friend_id 	朋友ID（聊天两人中的对方的ID）
	 * @param int 		$group_id 	群ID（群聊）
	 */
	public function get_room_id( $user_id = 0, $friend_id = 0, $group_id = 0, $chat_type = "friend"){
		if($chat_type == "friend"){
            $room_id = ($user_id*$friend_id)."11111";
        }else{
            $room_id = $group_id."22222";
        }
        return $room_id;
	}

	/**
	 * 获取聊天记录（分页）
	 */
	public function get_records($key,$page=1,$list_rows=10){
		$rt =$this->get_all_records($key);
		$total = count($rt);
		if($total > $start){
			$start = ($page-1)*$list_rows;
			$end = $page*$list_rows;
			$rt0 = array();
			for($i=$start; $i<$end; $i++){
				if($i >= $total){
					break;
				}
				$rt0[] = $rt[$i];
			}
			return $rt0;
		}else{				
			return array();
		}
	}

	/**
	 * 获取所有聊天记录
	 */
	public function get_all_records($key){
		$rt =$this->redis->get($key);
		if(!$rt){
			return array();
		}else{			
			return json_decode($rt,true);
		}
		
	}

	/**
	 * 添加聊天记录
	 */
	public function add_record($data){
		if(!isset($data["user_id"]) || !isset($data["room_id"]) ) {
			return false;
		}
		$key = "chat_".$data["room_id"];
		unset($data["room_id"]);
		$rs = $this -> get_all_records($key);

		if(!$rs){
			$rs[] = $data;
		}else{
			array_unshift($rs,$data);			
		}
		$this->redis ->set($key,json_encode($rs));
		return true;
	}

	/**
	 * 添加聊友
	 * @param $user_id 		用户ID
	 * @param $friend_id 	聊友ID
	 * @param $has_news		是否有新消息（0：没有， 1：有，默认没有（0））
	 */
	public function add_friend($user_id = 0, $friend_id = 0, $has_news = 0){
		if(intval($user_id) < 1 || intval($friend_id) < 1) {
			return false;
		}
		$key ="chat_user_".$user_id;
		$rs = $this->get_friends($user_id);
		$rs[$friend_id] = $has_news;
		$this->redis ->set($key,json_encode($rs));
		return true;		
	}

	/**
	 * 获取用户聊友列表
	 */
	public function get_friends($user_id){
		if(intval($user_id) < 1){
			return array();
		}
		$key ="chat_user_".$user_id;
		$rt = $this->redis->get($key);
		$rt = json_decode($rt,true);
		return $rt;
	}

	/**
	 * 添加群
	 */
	public function add_group($user_id=0, $group_id=0, $has_news=0){
		if(intval($user_id) < 1 || intval($group_id) < 1) {
			return false;
		}
		$key ="chat_group_".$user_id;
		$rs = $this->get_groups($user_id);
		$rs[$group_id] = $has_news;
		$this->redis ->set($key,json_encode($rs));
		return true;
	}

	/**
	 * 获取用户聊友列表
	 */
	public function get_groups($user_id){
		if(intval($user_id) < 1){
			return array();
		}
		$key ="chat_group_".$user_id;
		$rt = $this->redis->get($key);
		$rt = json_decode($rt,true);
		return $rt;
	}





////////////////////
//以下是数据库操作//
////////////////////
    /**
     * 获取用户信息
     * @param
     */
    public function get_user_info($id){
    	if(intval($id)<1){
    		return array();
    	}
    	$rt = Db::instance('mysql')->select('user_id,user_name,nick_name,user_picture as user_avatar')->from('dsc_users')->where('user_id='.$id)->query();
    	$rt = $rt[0];

    	$rt['user_avatar'] = $this->get_image_path($rt['user_avatar']);

    	return $rt;
    }

    /**
     * 获取用户列表
     * @param
     */
    public function get_user_list($ids){
    	if(empty($ids)){
    		return array();
    	}
    	$ids = implode(",",$ids);
    	$rt = Db::instance('mysql')->select('user_id,user_name,nick_name,user_picture as user_avatar')->from('dsc_users')->where("user_id in ($ids)")->query();
    	$rt0 = array();
    	if($rt){
    		foreach ($rt as $row){
    			$row['user_avatar'] = $this->get_image_path($row['user_avatar']);
    			$rt0[$row['user_id']] = $row;
    		}
    	}
    	return $rt0;
    }

    /**
     * 获取群信息
     * @param
     */
    public function get_group_info($id){
    	if(intval($id)<1){
    		return array();
    	}
    	$rt = Db::instance('mysql')->select('group_id,name,owner,users,admins,add_time')->from('dsc_users_im_group')->where("group_id = {$id}")->query();
    	return $rt[0];
    }


    /**
     * 获取oss信息
     */
	public function get_bucket_info()
	{
	    $res = Db::instance('mysql')->select('*')->from('dsc_oss_configure')->where('is_use = 1')->query();
	    $res = $res[0];
	    if ($res) {
	        $regional = substr($res["regional"], 0, 2);
	        if (($regional == "us") || ($regional == "ap")) {
	            $res["outside_site"] = "http://" . $res["bucket"] . ".oss-" . $res["regional"] . ".aliyuncs.com";
	            $res["inside_site"] = "http://" . $res["bucket"] . ".oss-" . $res["regional"] . "-internal.aliyuncs.com";
	        } else {
	            $res["outside_site"] = "http://" . $res["bucket"] . ".oss-cn-" . $res["regional"] . ".aliyuncs.com";
	            $res["inside_site"] = "http://" . $res["bucket"] . ".oss-cn-" . $res["regional"] . "-internal.aliyuncs.com";
	            if(empty($res["endpoint"])){
	                $res["endpoint"] = "http://" . $res["bucket"] . ".oss-cn-" . $res["regional"] . ".aliyuncs.com/";
	            }
	        }
	    }

	    return $res;
	}


	/**
	 * 获取图片络网地址
	 */
	public function get_image_path($image = "", $domain = 0)
	{
	    $no_image = "/mobile/resources/themes/default/img/no_image.jpg";
	    $bucket_info = $this->get_bucket_info();
	    $cfg = $this->get_shop_config();
	    if (strtolower(substr($image, 0, 4)) == "http") {
	        if(preg_match("/^(http:\/\/|http:\/\/).*$/",$image,$match)){
	            if(preg_match("/^(https:\/\/www.eggou.com\/|http:\/\/res.eggou.com\/).*$/",$image,$m)){
	                $url = str_replace($m[1],$bucket_info["endpoint"],$image);
	            }else{
	                $url = $image;
	            }
	        }else{
	            $url = $image;
	        }
	    } else if ($cfg["open_oss"] == 1) {
	        $url = (empty($image) ? $no_image : $bucket_info["endpoint"] . $image);
	    } else {
	        $base_url = (IS_ECSHOP ? dirname(__URL__) : __URL__);
	        $url = (empty($image) ? $no_image : (empty($domain) ? "../" . $image : $base_url . "/" . $image));
	    }
	    if($cfg["open_oss"] == 1) $url = str_replace('/../','/',$url);
	    return $url;
	}


	/**
	 * 获取系统配置
	 */
	public function get_shop_config()
	{	    
	    $cfg = Db::instance('mysql')->select('code,value')->from('dsc_shop_config')->query();
	    if($cfg){
	    	return $cfg;
	    }
	    return array();
	}
}

